var socket = {
    ws: undefined,
    status: false
}

const initSocket = () => {
    return new Promise((resolve, reject) => {
        let flag = false
        if ("WebSocket" in window) {
            setTimeout(() => {
                reject('连接超时')
            }, 5000)
            socket.ws = new WebSocket(process.env.VUE_APP_BASE_SOCKET);
            socket.ws.onopen = () => {
                socket.status = true
                resolve(true)
            };
            socket.ws.sendout = (data, ms = 30000) => {
                // 生成4位随机数+毫秒时间戳后6位
                let num = ''
                for (let i = 0; i < 4; i++){
                    num += Math.floor(Math.random() * 10)
                }
                let time = new Date().getTime() + ''
                time = '1' + time.substring(time.length - 6) + num
                data = JSON.parse(data)
                data.Uid = Number(time)
                return new Promise((resolve) => {
                    socket.ws.send(JSON.stringify(data));
                    let a = 's' + time
                    console.log(a)
                    socket[a] = (res) => {
                        resolve(res)
                    }
                    setTimeout(() => {
                        delete socket[a]
                        resolve({"StatusCode":301,"Data":"请求超时","Remark":"0","Uid": time})
                    }, ms)
                })
            }
            socket.ws.onmessage = evt => {
                let res = evt.data
                let backmsg = JSON.parse(res.replace('Response:',''))
                let a = 's' + backmsg.Uid
                console.log(a)
                if(socket[a]){
                    socket[a](backmsg)
                    delete socket[a]
                }
            };
            socket.ws.error = () => {
                console.log("通信异常");
                socket.status = false
                reject(false)
            };
            socket.ws.onclose = () => {
                console.log('执行关闭链接')
                socket.status = false
                if(!flag){
                    //异常断开连接
                    reject(false)
                }
                console.log("断开了连接");
            };
        } else {
            console.log("浏览器不支持WebSocket");
            socket.status = false
            reject(false)
        }
    })
}

function getLink() {
    if(socket.status){
        return Promise.resolve(socket)
    }
    return initSocket().then(value => {
        return Promise.resolve(socket)
    })
}

function closeWs() {
    socket.status = false
}


export {
    getLink, closeWs
}